<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'
import { WARNING_STATES } from '@/enum'
import { alarmApi } from '@/api'

const props = defineProps<{
  warningId: number
}>()
const emits = defineEmits<{
  (e: 'save-success'): void
}>()

const dialogRef = ref<InstanceType<typeof CustomDialog>>()
const formRef = ref<FormInstance>()

const info = reactive({
  content: '',
})
const rules = {
  content: [
    {
      required: true,
      message: '请输入忽略告警内容描述，字数在200个以内',
    },
  ],
}

async function clickSave(done: any) {
  const isValid = await formRef.value
    ?.validate()
    .catch(() => {
      done()
    })
  if (isValid) {
    try {
      await alarmApi.updateWarningByState({
        id: props.warningId,
        auditContent: info.content,
        state: WARNING_STATES.IGNORED,
      })
      done()
      close()
      ElMessage.success('保存成功')
      emits('save-success')
    }
    catch (e) {
      done() // 确保“保存”按钮的loading状态关闭
      console.log(e)
    }
  }
}

function open() {
  info.content = ''
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    title="忽略告警"
    width="600px"
    need-saving
    @confirm="clickSave"
  >
    <ElForm
      ref="formRef"
      :model="info"
      :rules="rules"
      label-position="top"
    >
      <ElFormItem label="忽略内容描述" prop="content">
        <ElInput
          v-model.trim="info.content"
          type="textarea"
          :autosize="{
            minRows: 6,
            maxRows: 10,
          }"
          autofocus
          :maxlength="200"
          :minlength="1"
          placeholder="请输入忽略告警内容描述，字数在200个以内"
        />
      </ElFormItem>
    </ElForm>
  </CustomDialog>
</template>
